﻿using System;
using System.Linq;

using agsXMPP.protocol.iq.roster;

using VSTalk.Engine.Core.XmppUtils;
using VSTalk.Model;

namespace VSTalk.Engine.Core.XmppConnection.RosterObserver
{
    public class RosterItemHandler
    {
        private readonly Client _client;

        public RosterItemHandler(Client client)
        {
            _client = client;
        }

        public void OnRoster(RosterItem item)
        {
            var bare = item.Jid.Bare.ToLower();
            var target = GetOrDefault(bare);
            if (target == null && item.Subscription != SubscriptionType.remove)
            {
                bool subscribed = RosterData.Subscribed(item);
                var jid = item.Jid;
                var name = RosterData.Name(item);
                var interlocutor = new Interlocutor
                {
                    Id = Guid.NewGuid(),
                    Name = name,
                    Server = jid.Server,
                    User = jid.User,
                    Subscribed = subscribed,
                };
                _client.Contacts.Add(interlocutor);
            }
            else if (target != null && item.Subscription != SubscriptionType.remove)
            {
                bool subscribed = RosterData.Subscribed(item);
                var jid = item.Jid;
                var name = RosterData.Name(item);
                target.Name = name;
                target.Server = jid.Server;
                target.User = jid.User;
                target.Subscribed = subscribed;
            }
            else if (target != null && item.Subscription == SubscriptionType.remove)
            {
                _client.Contacts.Remove(target);
            }
        }
        private Interlocutor GetOrDefault(string bare)
        {
            return _client.Contacts.FirstOrDefault(interlocutor => bare == XmppIdConverter.Jid(interlocutor).Bare.ToLower());
        }
    }
}